// 导航栏API服务
import express from 'express';
import { dbPool } from '../config/database.js';

const router = express.Router();

// 认证中间件
import jwt from 'jsonwebtoken';

function authenticateToken(req, res, next) {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
        return res.status(401).json({
            success: false,
            message: '访问令牌缺失'
        });
    }

    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = decoded;
        next();
    } catch (error) {
        return res.status(403).json({
            success: false,
            message: '无效的访问令牌'
        });
    }
}

// 获取用户信息
router.get('/users/profile', authenticateToken, async (req, res) => {
    try {
        const result = await dbPool.query(
            'SELECT id, username, email, role, avatar, last_login, created_at FROM users WHERE id = $1',
            [req.user.id]
        );
        
        if (result.rows.length === 0) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        const user = result.rows[0];
        res.json({
            success: true,
            data: {
                id: user.id,
                username: user.username,
                email: user.email,
                role: user.role,
                avatar: user.avatar,
                lastLogin: user.last_login,
                createdAt: user.created_at
            }
        });
    } catch (error) {
        console.error('获取用户信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取用户信息失败'
        });
    }
});

// 获取通知列表
router.get('/notifications', authenticateToken, async (req, res) => {
    try {
        const { limit = 10, offset = 0 } = req.query;
        
        // 获取用户通知总数
        const totalResult = await dbPool.query(
            'SELECT COUNT(*) FROM notifications WHERE user_id = $1',
            [req.user.id]
        );
        const total = parseInt(totalResult.rows[0].count);
        
        // 获取分页通知
        const result = await dbPool.query(
            'SELECT id, title, message, type, read, created_at FROM notifications WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3',
            [req.user.id, parseInt(limit), parseInt(offset)]
        );

        const userNotifications = result.rows.map(notification => ({
            id: notification.id,
            title: notification.title,
            message: notification.message,
            type: notification.type,
            read: notification.read,
            createdAt: notification.created_at
        }));

        res.json({
            success: true,
            data: userNotifications,
            pagination: {
                total: total,
                limit: parseInt(limit),
                offset: parseInt(offset),
                hasMore: parseInt(offset) + userNotifications.length < total
            }
        });
    } catch (error) {
        console.error('获取通知列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取通知列表失败'
        });
    }
});

// 标记通知为已读
router.post('/notifications/:id/read', authenticateToken, async (req, res) => {
    try {
        const notificationId = parseInt(req.params.id);
        
        // 检查通知是否存在且属于当前用户
        const checkResult = await dbPool.query(
            'SELECT id FROM notifications WHERE id = $1 AND user_id = $2',
            [notificationId, req.user.id]
        );
        
        if (checkResult.rows.length === 0) {
            return res.status(404).json({
                success: false,
                message: '通知不存在'
            });
        }

        // 更新通知为已读
        await dbPool.query(
            'UPDATE notifications SET read = true, read_at = CURRENT_TIMESTAMP WHERE id = $1',
            [notificationId]
        );

        // 获取更新后的通知信息
        const result = await dbPool.query(
            'SELECT * FROM notifications WHERE id = $1',
            [notificationId]
        );

        res.json({
            success: true,
            message: '通知已标记为已读',
            data: result.rows[0]
        });
    } catch (error) {
        console.error('标记通知为已读失败:', error);
        res.status(500).json({
            success: false,
            message: '标记通知为已读失败'
        });
    }
});

// 标记所有通知为已读
router.post('/notifications/mark-all-read', authenticateToken, async (req, res) => {
    try {
        // 更新所有未读通知为已读
        const result = await dbPool.query(
            'UPDATE notifications SET read = true, read_at = CURRENT_TIMESTAMP WHERE user_id = $1 AND read = false RETURNING id',
            [req.user.id]
        );

        res.json({
            success: true,
            message: '所有通知已标记为已读',
            data: {
                markedCount: result.rowCount
            }
        });
    } catch (error) {
        console.error('标记所有通知为已读失败:', error);
        res.status(500).json({
            success: false,
            message: '标记所有通知为已读失败'
        });
    }
});

// 获取徽章计数
router.get('/dashboard/badge-counts', authenticateToken, async (req, res) => {
    try {
        // 从数据库获取实时数据
        const [
            blogCount,
            productCount,

            messageCount
        ] = await Promise.all([
            dbPool.query('SELECT COUNT(*) FROM articles WHERE status = $1', ['published']),
            dbPool.query('SELECT COUNT(*) FROM products WHERE status = $1', ['active']),

            dbPool.query('SELECT COUNT(*) FROM notifications WHERE user_id = $1 AND read = false', [req.user.id])
        ]);

        const badgeCounts = {
            blog: parseInt(blogCount.rows[0].count),
            products: parseInt(productCount.rows[0].count),

            messages: parseInt(messageCount.rows[0].count)
        };

        res.json({
            success: true,
            data: badgeCounts,
            lastUpdated: new Date().toISOString()
        });
    } catch (error) {
        console.error('获取徽章计数失败:', error);
        res.status(500).json({
            success: false,
            message: '获取徽章计数失败'
        });
    }
});

// 获取导航栏统计数据
router.get('/navbar/stats', authenticateToken, async (req, res) => {
    try {
        // 并行获取所有统计数据
        const [
            userResult,
            notificationStats,
            recentNotifications,
            badgeCounts
        ] = await Promise.all([
            dbPool.query('SELECT id, username, email, role, avatar, last_login, created_at FROM users WHERE id = $1', [req.user.id]),
            dbPool.query('SELECT COUNT(*) as total, COUNT(CASE WHEN read = false THEN 1 END) as unread FROM notifications WHERE user_id = $1', [req.user.id]),
            dbPool.query('SELECT id, title, message, type, created_at FROM notifications WHERE user_id = $1 ORDER BY created_at DESC LIMIT 5', [req.user.id]),
            dbPool.query(`
                SELECT 
                    (SELECT COUNT(*) FROM articles WHERE status = 'published') as blog,
                    (SELECT COUNT(*) FROM products WHERE status = 'active') as products,
                    (SELECT COUNT(*) FROM orders WHERE status = 'pending') as orders,
                    (SELECT COUNT(*) FROM notifications WHERE user_id = $1 AND read = false) as messages
            `, [req.user.id])
        ]);

        const stats = {
            user: userResult.rows[0],
            notifications: {
                total: parseInt(notificationStats.rows[0].total),
                unread: parseInt(notificationStats.rows[0].unread),
                recent: recentNotifications.rows
            },
            badgeCounts: {
                blog: parseInt(badgeCounts.rows[0].blog),
                products: parseInt(badgeCounts.rows[0].products),
                orders: parseInt(badgeCounts.rows[0].orders),
                messages: parseInt(badgeCounts.rows[0].messages)
            },
            systemStatus: {
                online: true,
                lastUpdate: new Date().toISOString(),
                performance: '良好'
            }
        };

        res.json({
            success: true,
            data: stats
        });
    } catch (error) {
        console.error('获取导航栏统计数据失败:', error);
        res.status(500).json({
            success: false,
            message: '获取导航栏统计数据失败'
        });
    }
});

// 实时数据推送端点（WebSocket模拟）
router.get('/navbar/updates', authenticateToken, (req, res) => {
    try {
        // 设置服务器推送（SSE）
        res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*'
        });

        // 发送初始数据
        res.write(`data: ${JSON.stringify({
            type: 'initial',
            data: {
                badgeCounts: mockData.badgeCounts,
                unreadNotifications: mockData.notifications.filter(n => !n.read).length
            }
        })}\n\n`);

        // 定期推送更新
        const interval = setInterval(() => {
            // 模拟数据变化
            const hasUpdates = Math.random() > 0.7; // 30%的概率有更新
            
            if (hasUpdates) {
                const updateData = {
                    type: 'update',
                    data: {
                        badgeCounts: {
                            blog: Math.max(0, mockData.badgeCounts.blog + Math.floor(Math.random() * 2) - 1),
                            products: Math.max(0, mockData.badgeCounts.products + Math.floor(Math.random() * 3) - 1),
                            orders: Math.max(0, mockData.badgeCounts.orders + Math.floor(Math.random() * 2)),
                            messages: Math.max(0, mockData.badgeCounts.messages + Math.floor(Math.random() * 3) - 1)
                        },
                        timestamp: new Date().toISOString()
                    }
                };

                // 更新模拟数据
                mockData.badgeCounts = updateData.data.badgeCounts;

                res.write(`data: ${JSON.stringify(updateData)}\n\n`);
            }
        }, 10000); // 每10秒检查一次更新

        // 客户端断开连接时清理
        req.on('close', () => {
            clearInterval(interval);
            res.end();
        });

    } catch (error) {
        console.error('实时数据推送失败:', error);
        res.status(500).json({
            success: false,
            message: '实时数据推送失败'
        });
    }
});

// 健康检查端点
router.get('/health', (req, res) => {
    res.json({
        success: true,
        service: 'navbar-api',
        status: 'healthy',
        timestamp: new Date().toISOString(),
        version: '1.0.0'
    });
});

module.exports = router;